package com.wsg.dep.seq;


import com.wsg.dep.core.Cursored;

import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;

import static java.util.Arrays.copyOf;

/**
 * Provides static methods for managing a {@link SequenceGroup} object.
 */
class SequenceGroups
{

    /**
     * 向门控序列中新增序列
     * @param holder
     * @param updater
     * @param cursor
     * @param sequencesToAdd
     * @param <T>
     */
    static <T> void addSequences(
        final T holder,
        final AtomicReferenceFieldUpdater<T, Sequence[]> updater,
        final Cursored cursor,
        final Sequence... sequencesToAdd)
    {
        // 游标
        long cursorSequence;
        // 更新的序列
        Sequence[] updatedSequences;
        // 当前序列
        Sequence[] currentSequences;

        do
        {
            // 原子的获取当前的门控序列
            currentSequences = updater.get(holder);
            // 复制指定数组，并返回一个新的数组，新数组的长度可以指定。
            updatedSequences = copyOf(currentSequences, currentSequences.length + sequencesToAdd.length);
            // 获取当前的游标
            cursorSequence = cursor.getCursor();

            // 当前序列的长度
            int index = currentSequences.length;
            for (Sequence sequence : sequencesToAdd)
            {
                // 设置新增的门控序列开始游标为同一游标
                sequence.set(cursorSequence);
                // 添加至更新的序列中
                updatedSequences[index++] = sequence;
            }
        }
        // 由于上面的操作都是原子性的，如果因为其他现场修改导致的此处进入循环，会重新获取并拼接数据。
        while (!updater.compareAndSet(holder, currentSequences, updatedSequences));

        // 将新添加的 Sequence 对象的游标值更新到最新状态，保证数据的一致性和操作的正确性。
        cursorSequence = cursor.getCursor();
        for (Sequence sequence : sequencesToAdd)
        {
            // 更新新增门控的游标
            sequence.set(cursorSequence);
        }
    }

    /**
     * 移除门控
     * @param holder
     * @param sequenceUpdater
     * @param sequence
     * @param <T>
     * @return
     */
    static <T> boolean removeSequence(
        final T holder,
        final AtomicReferenceFieldUpdater<T, Sequence[]> sequenceUpdater,
        final Sequence sequence)
    {
        // 需要移除的门控数量
        int numToRemove;
        // 旧的门控
        Sequence[] oldSequences;
        // 新的门控
        Sequence[] newSequences;

        do
        {
            // 获取旧门控
            oldSequences = sequenceUpdater.get(holder);

            // 统计匹配的个数
            numToRemove = countMatching(oldSequences, sequence);

            if (0 == numToRemove)
            {
                break;
            }

            // 获取新的门控序列
            final int oldSize = oldSequences.length;
            newSequences = new Sequence[oldSize - numToRemove];

            for (int i = 0, pos = 0; i < oldSize; i++)
            {
                final Sequence testSequence = oldSequences[i];
                if (sequence != testSequence)
                {
                    newSequences[pos++] = testSequence;
                }
            }
        }
        while (!sequenceUpdater.compareAndSet(holder, oldSequences, newSequences));

        return numToRemove != 0;
    }

    /**
     * 计算匹配的数量
     * @param values
     * @param toMatch
     * @param <T>
     * @return
     */
    private static <T> int countMatching(T[] values, final T toMatch)
    {
        int numToRemove = 0;
        for (T value : values)
        {
            // 要求对比的对象重写toString方法
            if (value == toMatch) // Specifically uses identity
            {
                numToRemove++;
            }
        }
        return numToRemove;
    }
}
